import Api from '@/common/api.js';
import weixinPay from '@/common/wxPay.js';

export default class CommonPay {
	constructor(orderId = '', payAmount = null, url = '') {
		this.payType = '';
		this.orderId = orderId;
		this.payAmount = payAmount;
		this.url = url;
	}
	async getPayParams() {
		// uni.showModal({
		// 	title: '提示',
		// 	content: `payType: ${this.payType} orderId: ${this.orderId} payAmount: ${this.payAmount} url: ${this.url}`
		// });

		let params = {
				'trade_type': this.payType,
				'order_id': this.orderId
			},
			data = await Api.apiCall('post', Api.order.pay, params);
		// uni.showModal({
		// 	title: '提示',
		// 	content: `data: ${JSON.stringify(data)}`
		// });
		return data ? data : false;
		if (!data) {
			uni.showToast({
				title: data,
				icon: "none"
			});
		}
	}

	/**
	 * @param {res}
	 * @description 微信客户端支付 
	 */
	async weChatPay(payType) {
		this.payType = payType;
		let res = await this.getPayParams()
		// uni.showModal({
		// 	title: '提示',
		// 	content: `res: ${JSON.stringify(res)}`
		// });
		if (!res) return;
		uni.requestPayment({
			provider: "wxpay",
			orderInfo: {
				appid: res.appid,
				noncestr: res.nonce_str,
				// package: res1.package,
				package: "Sign=WXPay",
				// package: 'com.dfk.muyunlang',
				partnerid: "1572742411",
				prepayid: res.prepay_id,
				timestamp: res.timestamp,
				sign: res.sign,
			},
			success: (data) => {
				uni.redirectTo({
					url: `${ this.url }${ this.payType }&payAmount=${ this.payAmount }&orderId=${ this.orderId }`
				});
			},
			fail: (res) => {
				uni.showToast({
					title: '支付失败',
					icon: "none"
				});
			}
		});
	}

	/**
	 * @param {res}
	 * @description 支付宝客户端支付 
	 */
	async aliPay(payType) {
		this.payType = payType;
		let res = await this.getPayParams()
		if (!res) return;
		uni.requestPayment({
			provider: "alipay",
			orderInfo: res.sign,
			success: (data) => {
				uni.redirectTo({
					url: `${ this.url }${ this.payType }&payAmount=${ this.payAmount }&orderId=${ this.orderId }`
				});
			},
			fail: (err) => {
				uni.showToast({
					title: '支付失败',
					icon: "none"
				});
			}
		});
	}

	/**
	 * @param {res}
	 * @description 微信H5支付 
	 */
	async h5WechatPay(payType) {
		this.payType = payType;
		/**
		 * 微信支付有两种
		 * 判断是否在微信浏览器
		 * 	微信jsapi支付
		 */
		let isWechat = weixinPay.isWechat();
		if (!isWechat) {
			uni.showToast({
				title: '请在微信浏览器内支付',
				icon: "none"
			});
			return false;
		}
		let data = await this.getPayParams();
		if (data) {
			this.checkWXJSBridge(data.choose_data);
		} else {
			window.location.href = data.msg
			return;
		}
	}
	/**
	 * @param {res}
	 * @description 微信小程序支付 
	 */
	async miniAppWechatPay(payType) {
		this.payType = payType;
		let res = await this.getPayParams();
		if (res) {
			let data = res.choose_data;
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: data.timeStamp,
				nonceStr: data.nonceStr,
				package: data.package,
				signType: data.signType,
				paySign: data.paySign,
				success: (e) => {
					if (e.errMsg === 'requestPayment:ok') {
						uni.redirectTo({
							url: `${this.url}${this.payType}&payAmount=${this.payAmount}&orderId=${this.orderId}`
						});
					}
				}
			});
		} else {
			this.$common.errorToShow(res.msg)
		}
	}
	checkWXJSBridge(data) {
		let interval = setInterval(() => {
			if (typeof window.WeixinJSBridge != 'undefined') {
				clearTimeout(interval)
				this.onBridgeReady(data)
			}
		}, 200)
	}
	onBridgeReady(data) {
		window.WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				appId: data.appId, // 公众号名称，由商户传入
				timeStamp: data.timeStamp, // 时间戳，自1970年以来的秒数
				nonceStr: data.nonceStr, // 随机串
				package: data.package,
				signType: data.signType, // 微信签名方式：
				// signType: 'MD5', // 微信签名方式：
				// paySign: data.paySign ,// 微信签名
				paySign: data.paySign, // 微信签名

			}, (res) => {
				if (res.err_msg === 'get_brand_wcpay_request:ok') {
					uni.showToast({
						title: '支付成功',
						icon: "none"
					});
					setTimeout(() => {
						uni.redirectTo({
							url: this.url + this.payType + '&payAmount=' + this.payAmount + '&orderId=' + this.orderId
						});
					}, 1000)
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					uni.showToast({
						title: '取消支付',
						icon: "none"
					});
				} else {
					uni.showToast({
						title: '支付失败',
						icon: "none"
					});
				}

			}
		)
	}
}
